<template>
  <a-layout class="user-center-container">
    <a-layout-header class="header">
      <div class="logo">蜗牛AI在线课堂</div>
      <div class="header-right">
        <a-button @click="$router.push('/')">返回首页</a-button>
      </div>
    </a-layout-header>

    <a-layout-content class="content">
      <a-row :gutter="24">
        <!-- 左侧用户信息 -->
        <a-col :span="6">
          <div class="user-info-card">
            <div class="user-avatar">
              <a-avatar :src="userInfo?.filePath" :size="80" />
            </div>
            <div class="user-details">
              <h3>{{ userInfo?.username }}</h3>
              <p>邮箱：{{ userInfo?.email }}</p>
              <p>手机号：{{ userInfo?.phone }}</p>
            </div>
            <a-button type="link" @click="showEditModal = true">编辑信息</a-button>
            <a-button type="link" @click="showPasswordModal = true">修改密码</a-button>
            <ContributionCalendar :data="contributionData" />
          </div>
        </a-col>

        <!-- 右侧主要内容 -->
        <a-col :span="18">
          <a-tabs :activeKey="activeTab" @change="onTabChange">
            <a-tab-pane key="teams" tab="我的战队" />
            <a-tab-pane key="questions" tab="我的问题" />
            <a-tab-pane key="doc" tab="视频文档" />
            <a-tab-pane key="notes" tab="我的笔记" />
            <a-tab-pane key="points" tab="我的积分" />
            <a-tab-pane key="orders" tab="我的订单" />
            <a-tab-pane key="reviews" tab="审核成员" />
             <a-tab-pane key="posts" tab="审核帖子" />
          </a-tabs>
          <router-view />
        </a-col>
      </a-row>
      <!-- 编辑信息弹窗 -->

      <a-modal v-model:open="showEditModal" title="编辑个人信息" @ok="handleUpdateUser" :confirmLoading="loading" ok-text="保存"
        cancel-text="取消">
        <a-form layout="vertical">
          <!-- 头像上传（显示图片+上传） -->
          <a-form-item label="头像" :wrapper-col="{ span: 24 }">
            <div style="text-align: center;">
              <a-upload name="filePath" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
                :before-upload="beforeAvatarUpload" :custom-request="handleAvatarUpload">
                <template v-if="editForm.filePath">
                  <img :src="editForm.filePath" alt="头像"
                    style="width: 100%; height: 100%; object-fit: cover; border-radius: 4px;" />
                </template>
                <template v-else>
                  <div>
                    <plus-outlined />
                    <div style="margin-top: 8px;">上传头像</div>
                  </div>
                </template>
              </a-upload>
              <div v-if="editForm.filePath" style="margin-top: 8px;">
                <a-button size="small" @click="editForm.filePath = ''">移除头像</a-button>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="用户名">
            <a-input v-model:value="editForm.username" />
          </a-form-item>
          <a-form-item label="邮箱">
            <a-input v-model:value="editForm.email" />
          </a-form-item>
          <a-form-item label="手机号">
            <a-input v-model:value="editForm.phone" />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 新增修改密码的弹窗 -->
      <a-modal v-model:open="showPasswordModal" title="修改密码" @ok="handleUpdatePassword" :closable="modalProps.closable"
        :maskClosable="modalProps.maskClosable" :footer="modalProps.footer" :confirmLoading="passwordLoading"
        ok-text="确认修改" cancel-text="取消">
        <template v-if="userInfo?.forcePasswordChange">
          <a-alert message="系统检测到您使用的是默认密码，请先修改密码" type="warning" show-icon />
          <br />
        </template>
        <a-form layout="vertical" @finish="handleUpdatePassword">
          <a-form-item v-if="!userInfo.forcePasswordChange" label="原密码" required>
            <a-input-password v-model:value="passwordForm.oldPassword" />
          </a-form-item>
          <a-form-item label="新密码" required>
            <a-input-password v-model:value="passwordForm.newPassword" />
          </a-form-item>
          <a-form-item label="确认新密码" required>
            <a-input-password v-model:value="passwordForm.confirmPassword" />
          </a-form-item>
        </a-form>
        <template #footer v-if="modalProps.footer === null">
          <a-button @click="handleUpdatePassword" type="primary">确定</a-button>
        </template>
      </a-modal>

    </a-layout-content>
  </a-layout>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { getUser, updateUser, updatePassword, getUserById } from '@/api/sysUserController.ts'
import { uploadPic } from '@/api/bizMediaFileController'
import ContributionCalendar from '@/components/ContributionCalendar.vue'
import { getUserCalendarRecords } from '@/api/taskActionController'
import dayjs from 'dayjs'

const baseUrl = import.meta.env.VITE_PIC_BASE_URL
const route = useRoute();


const router = useRouter()
const tabKeyToRoute = {
  posts: 'posts',
  teams: 'teams',
  questions: 'questions',
  exams: 'exams',
  doc: 'doc',
  notes: 'notes',
  points: 'points',
  orders: 'orders',
  game: 'game',
  reviews: 'reviews',
}
const routeToTabKey = Object.fromEntries(Object.entries(tabKeyToRoute).map(([k, v]) => [v, k]))
const activeTab = ref('teams')

// 监听路由变化，切换tab
watch(
  () => route.fullPath,
  () => {
    const sub = route.path.split('/')[2]
    if (routeToTabKey[sub]) {
      activeTab.value = routeToTabKey[sub]
    }
  },
  { immediate: true }
)

const onTabChange = (key: string) => {
  router.push({ path: `/user/${tabKeyToRoute[key]}` })
  activeTab.value = key
}

// 响应式数据
const todayProgress = ref(75)
const weekProgress = ref(60)

// 用户信息
const userInfo = ref<any>(null)
const showEditModal = ref(false)
const loading = ref(false)

//密码信息
const showPasswordModal = ref(false)
const passwordLoading = ref(false)

// 定义 modalProps
const modalProps = ref({
  closable: true,
  maskClosable: true,
  footer: undefined,
});

// 编辑表单数据
const editForm = reactive({
  userId: null,
  username: '',
  email: '',
  phone: '',
  filePath: '',
})

// 修改密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 获取用户信息
const loadUserData = async (targetUserId?: number) => {
  try {
    // 如果没有传入targetUserId（如普通个人中心），则获取当前登录用户的ID
    const userId = targetUserId ?? getCurrentUserId();
    const res = await getUserById({ userId });
    console.log('用户数据:', res);


    if (res.data.code === 0) {
      userInfo.value = res.data.data;
      console.log('用户数据加载成功:', userInfo.value);

      // 检查是否需要强制修改密码
      if (userInfo.value?.forcePasswordChange) {
        showPasswordModal.value = true;
      }
    }
  } catch (err) {
    console.error('加载用户失败:', err);
  }
};

// 获取当前登录用户的ID（
const getCurrentUserId = () => {
  const user = JSON.parse(localStorage.getItem('userInfo'));
  return user?.userId;
};

// 更新用户信息
const handleUpdateUser = async () => {
  loading.value = true;
  try {
    const payload = {
      userId: userInfo.value.userId, // 从当前用户信息获取ID
      username: editForm.username,
      email: editForm.email,
      phone: editForm.phone,
      filePath: editForm.filePath
    };

    const { data } = await updateUser(payload);
    if (data.code === 0) {
      message.success('用户信息更新成功');
      showEditModal.value = false;
      await loadUserData(); // 重新获取用户信息更新界面
    } else {
      message.error(data.message || '更新失败');
    }
  } catch (error) {
    console.error('更新用户错误:', error);
    message.error('更新失败，请重试');
  } finally {
    loading.value = false;
  }
};


// 修改密码方法
const handleUpdatePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    return message.error('两次新密码不一致')
  }

  passwordLoading.value = true
  try {
    // 构建不同的请求参数
     const params: any = { newPassword: passwordForm.newPassword };

    // 只有非强制修改时才添加 oldPassword
    if (!userInfo.value?.forcePasswordChange) {
      params.oldPassword = passwordForm.oldPassword;
    }else{
      passwordForm.oldPassword='';
    }
    console.log('提交参数:', params);
    const res = await updatePassword(params)
    if (res.data.code === 0) {
      message.success('密码修改成功,请重新登录')
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      showPasswordModal.value = false
      // 清空表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      // 如果是强制修改流程，刷新用户信息
      if (route.query.forcePwdChange) {
        await loadUserData();
      }
      // 跳转到登录页
      router.push('/login');
    } else {
      message.error(res.data.message || '密码修改失败')
    }
  } catch (err) {
    console.error(err)
    message.error('请求失败')
  } finally {
    passwordLoading.value = false
  }
}

// 弹窗打开时填充表单
watch(showEditModal, (val) => {
  if (val && userInfo.value) {
    editForm.userId = userInfo.value.userId; // 确保设置userId
    editForm.username = userInfo.value.username;
    editForm.email = userInfo.value.email;
    editForm.phone = userInfo.value.phone;
    editForm.filePath = userInfo.value.filePath;
  }
});

// 上传头像逻辑
const handleAvatarUpload = async ({ file }: { file: File }) => {
  try {
    loading.value = true;
    const { data } = await uploadPic({}, file);
    if (data?.code === 0 && data.data?.filePath) {
      // 直接使用后端返回的完整MinIO地址（假设后端已返回完整URL）
      // form.filePath = data.data.filePath;
      // 或者如果后端只返回相对路径：
      editForm.filePath = `${baseUrl}${data.data.filePath}`;
      message.success('头像上传成功');
    } else {
      message.error(data?.message || '头像上传失败');
    }
  } catch (error) {
    console.error('头像上传错误:', error);
    message.error('头像上传失败');
  } finally {
    loading.value = false;
  }
};
// 头像上传前校验
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('头像图片大小不能超过2MB!');
    return false;
  }
  return true;
};

// 贡献日历模拟数据（实际应从后端获取）
function getFakeData(days = 126) {
  const arr = []
  const centerIdx = Math.floor(days / 2)
  const today = new Date()
  // 1. 生成左边（过去的日期）
  for (let i = 0; i < centerIdx; i++) {
    const d = new Date(today)
    d.setDate(today.getDate() - (centerIdx - i))
    const dateStr = d.toISOString().slice(0, 10)
    arr.push({
      date: dateStr,
      loggedIn: true,
      watchedVideo: Math.random() > 0.5,
      wroteNote: Math.random() > 0.7
    })
  }
  // 2. 今天
  arr.push({
    date: today.toISOString().slice(0, 10),
    loggedIn: true,
    watchedVideo: Math.random() > 0.5,
    wroteNote: Math.random() > 0.7
  })
  // 3. 生成右边（未来的日期，全部灰色）
  for (let i = 1; i < days - centerIdx; i++) {
    const d = new Date(today)
    d.setDate(today.getDate() + i)
    const dateStr = d.toISOString().slice(0, 10)
    arr.push({
      date: dateStr,
      loggedIn: false,
      watchedVideo: false,
      wroteNote: false
    })
  }
  return arr
}

const contributionData = ref([])

const calendarMonth = ref(dayjs().format('YYYY-MM'))

const fetchCalendarData = async () => {
  // 只显示calendarMonth的所有天
  const month = calendarMonth.value
  const daysInMonth = dayjs(month + '-01').daysInMonth()
  const arr = []
  const res = await getUserCalendarRecords({ month })
  const map = (res.data && res.data.code === 0 && res.data.data) ? res.data.data : {}
  for (let i = 1; i <= daysInMonth; i++) {
    const date = dayjs(month + '-' + String(i).padStart(2, '0')).format('YYYY-MM-DD')
    const tasks = map[date] || []
    arr.push({
      date,
      loggedIn: tasks.length > 0,
      watchedVideo: false,
      wroteNote: false,
      tasks // 传递任务名数组
    })
  }
  contributionData.value = arr
}

watch(contributionData, (val) => {
  console.log('watch contributionData for calendar:', val, 'length:', val.length)
}, { immediate: true })

// 作业相关
const assignmentColumns = [
  { title: '作业标题', dataIndex: 'title', key: 'title' },
  { title: '课程', dataIndex: 'course', key: 'course' },
  { title: '截止时间', dataIndex: 'deadline', key: 'deadline' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '分数', dataIndex: 'score', key: 'score' },
  { title: '操作', key: 'action' }
]

const assignments = reactive([
  {
    id: 1,
    title: 'AI基础概念作业',
    course: 'AI智能体开发实战',
    deadline: '2024-01-20',
    status: '待完成',
    score: null
  },
  {
    id: 2,
    title: 'Vue3组件开发作业',
    course: 'Vue3实战开发',
    deadline: '2024-01-18',
    status: '已完成',
    score: 85
  }
])

// 考试相关
const examColumns = [
  { title: '考试名称', dataIndex: 'title', key: 'title' },
  { title: '课程', dataIndex: 'course', key: 'course' },
  { title: '考试时间', dataIndex: 'examTime', key: 'examTime' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '分数', dataIndex: 'score', key: 'score' },
  { title: '操作', key: 'action' }
]

const exams = reactive([
  {
    id: 1,
    title: 'AI基础概念考试',
    course: 'AI智能体开发实战',
    examTime: '2024-01-15',
    status: '已完成',
    score: 88
  },
  {
    id: 2,
    title: 'Vue3基础考试',
    course: 'Vue3实战开发',
    examTime: '2024-01-25',
    status: '待考试',
    score: null
  }
])

// 方法
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    '待完成': 'orange',
    '已完成': 'green',
    '已过期': 'red'
  }
  return colors[status] || 'default'
}

const getExamStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    '待考试': 'orange',
    '已完成': 'green',
    '进行中': 'blue'
  }
  return colors[status] || 'default'
}

const refreshAssignments = () => {
  console.log('刷新作业')
}

const submitAssignment = (assignment: any) => {
  console.log('提交作业:', assignment.title)
}

const startNewExam = () => {
  console.log('开始新考试')
}

const takeExam = (exam: any) => {
  console.log('参加考试:', exam.title)
}

onMounted(async () => {
  // 优先从路由参数获取 userId（强制修改密码场景）
  const targetUserId = route.query.userId ? Number(route.query.userId) : null;
  console.log('请求参数:', { userId: targetUserId });

  // checkUserLogin()
  await loadUserData(targetUserId)
  await fetchCalendarData()
  // 检查是否需要强制修改密码
  if (route.query.forcePasswordChange === 'true') {
    showPasswordModal.value = true;
    message.warning('请先修改您的默认密码');

    // 特殊处理：隐藏关闭按钮，必须修改才能继续
    modalProps.value = {
      closable: false,
      maskClosable: false,
      footer: undefined
    };
  }
})
</script>

<style scoped>
.user-center-container {
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
}

.header-right {
  display: flex;
  gap: 12px;
}

.content {
  padding: 24px;
  background: #f5f5f5;
}

.user-info-card {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 16px;
  text-align: center;
}

.user-avatar {
  margin-bottom: 16px;
}

.user-details h3 {
  margin-bottom: 8px;
  color: #333;
}

.user-details p {
  color: #666;
  margin-bottom: 4px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 16px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.progress-card {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
}

.progress-card h4 {
  margin-bottom: 12px;
  color: #333;
}

.progress-item {
  margin-bottom: 12px;
}

.progress-item span {
  display: block;
  margin-bottom: 4px;
  color: #666;
  font-size: 12px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}
</style>
